import 'dart:async';
import 'dart:io';

import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/bean/check_in_statistics_group_info_response_bean.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/bean/check_in_statistics_sort_type.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/check_in_statistics_view_model.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_classify_button_select_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_department_button_select_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_in_statistics_classify_button_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_in_statistics_filter_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_in_statistics_more_button_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_in_statistics_top_bar_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_in_statistics_two_page_view_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/check_terminal_button_select_widget.dart';
import 'package:e_reception_flutter/ui/check_in_statistics/widgets/pages/check_in_statistics_list_response_bean.dart';
import 'package:e_reception_flutter/ui/company/company_choose_terminal_list/bean/company_choose_terminal_response_bean.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/utils/vg_toast_utils.dart';
import 'package:e_reception_flutter/vg_widgets/vg_mixin/navigator_page_mixin.dart';
import 'package:flutter/material.dart';
import 'package:upgrade_flutter/upgrade_flutter.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_sp_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import 'bean/check_in_statistics_filter_type.dart';

/// 打卡统计今日访客分组页面
///
/// @author: zengxiangxi
/// @createTime: 3/25/21 11:24 AM
/// @specialDemand:
class CheckInStatisticsPage extends StatefulWidget {
  ///路由名称
  static const String ROUTER = "CheckInStatisticsPage";

  final String isVeryClassifyType;
  final String departmentIds;
  final String classIds;
  final String departmentName;
  final String listTerminalBean;

  const CheckInStatisticsPage(
      {Key key,
      this.isVeryClassifyType,
      this.departmentIds,
      this.classIds,
      this.departmentName, this.listTerminalBean})
      : super(key: key);

  @override
  CheckInStatisticsPageState createState() => CheckInStatisticsPageState();

  ///跳转方法
  static Future<dynamic> navigatorPush(BuildContext context) async {
    //先读缓存中的筛选值
    String isVeryClassifyType = await SharePreferenceUtil.getString(
        "sp_check_in_statistics_is_very_care" +
            UserRepository.getInstance().getCompanyId());

    String departmentIds = await SharePreferenceUtil.getString(
        "sp_check_in_is_very_departmentIds" +
            UserRepository.getInstance().getCompanyId());

    String classIds = await SharePreferenceUtil.getString(
        "sp_check_in_is_very_classIds" +
            UserRepository.getInstance().getCompanyId());

    String departmentName = await SharePreferenceUtil.getString(
        "sp_check_in_is_very_departmentName" +
            UserRepository.getInstance().getCompanyId());

    String listTerminalBean = await SharePreferenceUtil.getString(
        "sp_check_in_is_very_deviceHsn" +
            UserRepository.getInstance().getCompanyId());

    return RouterUtils.routeForFutureResult(
      context,
      CheckInStatisticsPage(
        isVeryClassifyType: isVeryClassifyType,
        departmentIds: departmentIds,
        classIds: classIds,
        departmentName: departmentName,
        listTerminalBean: listTerminalBean,
      ),
      routeName: CheckInStatisticsPage.ROUTER,
    ).then((value) {
      //每次返回都走一边首页刷新打卡数字接口
      VgEventBus.global.send(new MonitoringIndexPageClass());
    });
  }
}

///保留打卡记录选项类型
//  String SP_CHECK_IN_STATISTICS_IS_VERY_CARE =
//     "sp_check_in_statistics_is_very_care"+UserRepository.getInstance().getCompanyId();

// ignore: non_constant_identifier_names
// String SP_CHECK_IN_IS_VERY_DEPARTMENTIDS =
//    "sp_check_in_is_very_departmentIds"+UserRepository.getInstance().getCompanyId();

// String SP_CHECK_IN_IS_VERY_CLASSIDS =
//     "sp_check_in_is_very_classIds"+UserRepository.getInstance().getCompanyId();

class CheckInStatisticsPageState extends BaseState<CheckInStatisticsPage>
    with
        TickerProviderStateMixin,
        AutomaticKeepAliveClientMixin,
        NavigatorPageMixin {
  CheckInStatisicsViewModel viewModel;

  List<StreamSubscription> _streamSubscriptionList = List();

  //当前日期（凌晨）
  DateTime currentTimeByWeekHours;

  //分组详情
  CheckInStatisticsGroupInfoDataBean groupInfoDataBean;

  //各列表通知更新
  StreamController<CheckInStatisticsFilterType>
      refreshMulitiAllListStreamController = StreamController.broadcast();

  //类型切换通知
  StreamController<Null> changeFilterTypeStreamController =
      StreamController.broadcast();

  // //各列表通知更新
  // StreamController<Null> refreshAllListStreamController =
  // StreamController.broadcast();

  //过滤器的值
  ValueNotifier<CheckInStatisticsFilterType> filterValueNotifier;

  //排序方式 默认最早
  ValueNotifier<CheckInStatisticsSortType> sortValueNotifier;

  //PageController
  PreloadPageController pageController;

  //刷脸总数值
  ValueNotifier<int> facedCountValueNotifier;

  //未刷脸总数值
  ValueNotifier<int> unFacedCountValueNotifier;

  //从列表返出的值
  ValueNotifier<CheckInStatisticsListDataBean> infoValueNotifier;

  //过滤类型
  CheckInStatisticsClassifyType classifyType;

  CheckInStatisticsListDataBean checkInStatisticsListDataBean;

  int _currentPage = 0;

  StreamSubscription classEventSubscription;

  StreamSubscription deviceEventSubscription;

  StreamSubscription departmentEventSubscription;

  String departmentIds;
  String classIds;

  String departmentName;

  String deviceHsnList;

  ///获取state
  static CheckInStatisticsPageState of(BuildContext context) {
    return context.findAncestorStateOfType<CheckInStatisticsPageState>();
  }

  @override
  void initState() {
    super.initState();
    if (widget?.departmentName != null) {
      departmentName = widget?.departmentName;
    }
    checkInStatisticsListDataBean = CheckInStatisticsListDataBean();
    viewModel = CheckInStatisicsViewModel(this);
    if (widget?.isVeryClassifyType == "CheckInStatisticsClassifyType.All") {
      classifyType = CheckInStatisticsClassifyType.All;
    } else if (widget?.isVeryClassifyType ==
        "CheckInStatisticsClassifyType.VeryCare") {
      classifyType = CheckInStatisticsClassifyType.VeryCare;
    } else if (widget?.isVeryClassifyType ==
        "CheckInStatisticsClassifyType.Department") {
      classifyType = CheckInStatisticsClassifyType.Department;
      departmentIds = widget?.departmentIds;
    } else if (widget?.isVeryClassifyType ==
        "CheckInStatisticsClassifyType.Class") {
      classifyType = CheckInStatisticsClassifyType.Class;
      classIds = widget?.classIds;
    }else if (widget?.isVeryClassifyType ==
        "CheckInStatisticsClassifyType.Device") {
      classifyType = CheckInStatisticsClassifyType.Device;
      deviceHsnList = widget?.listTerminalBean;
    }
    // classifyType = !(widget?.isVeryClassifyType ?? false)
    //     ? CheckInStatisticsClassifyType.All
    //     : CheckInStatisticsClassifyType.VeryCare;
    pageController = PreloadPageController(initialPage: 0);
    filterValueNotifier = ValueNotifier(CheckInStatisticsFilterType.finishFace);
    sortValueNotifier = ValueNotifier(CheckInStatisticsSortType.latest);
    facedCountValueNotifier = ValueNotifier(0);
    unFacedCountValueNotifier = ValueNotifier(0);
    infoValueNotifier = ValueNotifier(null);
    viewModel?.state?.infoValueNotifier?.addListener(() {
      checkInStatisticsListDataBean = infoValueNotifier?.value;
    });
    initCurrentDate();
    initListener();
  }

  initListener() {
    pageController?.addListener(_pageListener);
    // 因为弹窗后返回刷新了 所以暂时不用自动刷新
    // addPageListener(onPop:(){
    //   //页面切换 更新请求
    //   print("回到打卡记录页面：刷新操作");
    //   refreshMulitiAllListStreamController?.add(null);
    // });
    classEventSubscription =
        VgEventBus.global.on<ClassIdsRefreshEvent>().listen((event) {
      if ((event?.MClassList?.length ?? 0) == 0) {
        VgToastUtils.toast(context, "暂无班级");
        VgEventBus.global.send(ClassAndDepartmentIdsEvent(null, null,null));
        return;
      }
      if (event?.MClassList?.length == 1) {
        if (event?.MClassList == null) {
          return;
        }
        SharePreferenceUtil.putString(
            "sp_check_in_is_very_departmentName" +
                UserRepository.getInstance().getCompanyId(),
            event?.MClassList[0]?.classname);
        departmentName = event?.MClassList[0]?.classname;
        VgEventBus.global.send(
            ClassAndDepartmentIdsEvent(event?.MClassList[0]?.classid, null,null));
      } else {
        //跳转到班级选择
        CheckButtonSelectClassWidget.navigatorPush(
                context, classIds)
            .then((value) {
          if(value?.editText=="" || value?.editText==null){
            // if(widget?.departmentIds!=null && widget?.departmentIds!=""){
            //   departmentIds = widget?.departmentIds;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_is_very_departmentIds" +
            //           UserRepository.getInstance().getCompanyId(),
            //       departmentIds);
            //   classifyType = CheckInStatisticsClassifyType.Department;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_statistics_is_very_care" +
            //           UserRepository.getInstance().getCompanyId(),
            //       classifyType.toString());
            // }
            // if(widget?.listTerminalBean!=null && widget?.listTerminalBean!=""){
            //   deviceHsnList = widget?.listTerminalBean;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_is_very_deviceHsn" +
            //           UserRepository.getInstance().getCompanyId(),
            //       deviceHsnList);
            //   classifyType = CheckInStatisticsClassifyType.Device;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_statistics_is_very_care" +
            //           UserRepository.getInstance().getCompanyId(),
            //       classifyType.toString());
            // }
            return;
          }
          if (value?.value != "" || value?.value != null) {
            if ((value?.value?.split(",")?.length ?? 0) == 1) {
              SharePreferenceUtil.putString(
                  "sp_check_in_is_very_departmentName" +
                      UserRepository.getInstance().getCompanyId(),
                  value?.editText);
              departmentName = value?.editText;
            }
            VgEventBus.global
                .send(ClassAndDepartmentIdsEvent(value?.value, null,null));
          }
        });
      }
    });

    deviceEventSubscription =
        VgEventBus.global.on<DeviceIdsRefreshEvent>().listen((event) {
          List<String> listStr = List<String>();
          List<String> listDeviceHsns = deviceHsnList?.split(",");
          if ((event?.MHsnList?.length ?? 0) == 0) {
            VgToastUtils.toast(context, "暂无设备");
            VgEventBus.global.send(ClassAndDepartmentIdsEvent(null, null,null));
            return;
          }
          if (event?.MHsnList?.length == 1) {
            if (event?.MHsnList == null) {
              return;
            }
            SharePreferenceUtil.putString(
                "sp_check_in_is_very_departmentName" +
                    UserRepository.getInstance().getCompanyId(),
                event?.MHsnList[0]?.getTerminalName());
            departmentName = event?.MHsnList[0]?.getTerminalName();
            event?.MHsnList?.forEach((element) {
              listStr?.add(element?.hsn);
            });
            VgEventBus.global.send(
                ClassAndDepartmentIdsEvent(null, null,VgStringUtils.getSplitStr(listStr,symbol: ",")));
          } else {
            List<CompanyChooseTerminalListItemBean> selectedList = List<CompanyChooseTerminalListItemBean>();
            listDeviceHsns?.forEach((element) {
              CompanyChooseTerminalListItemBean bean = CompanyChooseTerminalListItemBean();
              bean?.hsn = element;
              // bean?.terminalName = element?.terminalName;
              selectedList?.add(bean);
            });
            //跳转到设备选择
            CheckTerminalSelectPage.navigatorPush(context, selectedList).then((value){
              if((value?.length??0)==0){
                // if(widget?.departmentIds!=null && widget?.departmentIds!=""){
                //   departmentIds = widget?.departmentIds;
                //   SharePreferenceUtil.putString(
                //       "sp_check_in_is_very_departmentIds" +
                //           UserRepository.getInstance().getCompanyId(),
                //       departmentIds);
                //   classifyType = CheckInStatisticsClassifyType.Department;
                //   SharePreferenceUtil.putString(
                //       "sp_check_in_statistics_is_very_care" +
                //           UserRepository.getInstance().getCompanyId(),
                //       classifyType.toString());
                // }
                // if(widget?.classIds!=null && widget?.classIds!=""){
                //   classIds = widget?.classIds;
                //   SharePreferenceUtil.putString(
                //       "sp_check_in_is_very_classIds" +
                //           UserRepository.getInstance().getCompanyId(),
                //       classIds);
                //   classifyType = CheckInStatisticsClassifyType.Class;
                //   SharePreferenceUtil.putString(
                //       "sp_check_in_statistics_is_very_care" +
                //           UserRepository.getInstance().getCompanyId(),
                //       classifyType.toString());
                // }
                return;
              }
              if ((value?.length??0) != 0) {
                value?.forEach((element) {
                  listStr?.add(element?.hsn);
                });
                if ((value?.length??0) == 1) {
                  SharePreferenceUtil.putString(
                      "sp_check_in_is_very_departmentName" +
                          UserRepository.getInstance().getCompanyId(),
                      value[0]?.getTerminalName(0));
                  departmentName = value[0]?.getTerminalName(0);
                }
                VgEventBus.global
                    .send(ClassAndDepartmentIdsEvent(null, null,VgStringUtils.getSplitStr(listStr,symbol: ",")));
              }
            });
          }
        });

    departmentEventSubscription =
        VgEventBus.global.on<DepartmentIdsRefreshEvent>().listen((event) {
      if ((event?.mDepartment?.length ?? 0) == 0) {
        VgToastUtils.toast(context, "暂无部门");
        VgEventBus.global.send(ClassAndDepartmentIdsEvent(null, null,null));
        return;
      }
      if (event?.mDepartment?.length == 1) {
        if (event?.mDepartment == null) {
          return;
        }
        SharePreferenceUtil.putString(
            "sp_check_in_is_very_departmentName" +
                UserRepository.getInstance().getCompanyId(),
            event?.mDepartment[0]?.department);
        departmentName = event?.mDepartment[0]?.department;
        VgEventBus.global.send(ClassAndDepartmentIdsEvent(
            null, event?.mDepartment[0]?.departmentid,null));
      } else {
        //跳转到部门选择
        CheckButtonSelectDepartmentWidget.navigatorPush(
                context, event?.mDepartment, departmentIds)
            .then((value) {
          if(value?.editText=="" || value?.editText==null){
            // if(widget?.classIds!=null && widget?.classIds!=""){
            //   classIds = widget?.classIds;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_is_very_classIds" +
            //           UserRepository.getInstance().getCompanyId(),
            //       classIds);
            //   classifyType = CheckInStatisticsClassifyType.Class;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_statistics_is_very_care" +
            //           UserRepository.getInstance().getCompanyId(),
            //       classifyType.toString());
            // }if(widget?.listTerminalBean!=null && widget?.listTerminalBean!=""){
            //   deviceHsnList = widget?.listTerminalBean;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_is_very_deviceHsn" +
            //           UserRepository.getInstance().getCompanyId(),
            //       deviceHsnList);
            //   classifyType = CheckInStatisticsClassifyType.Device;
            //   SharePreferenceUtil.putString(
            //       "sp_check_in_statistics_is_very_care" +
            //           UserRepository.getInstance().getCompanyId(),
            //       classifyType.toString());
            // }
            return;
          }
          if (value?.value != "" || value?.value != null) {
            if ((value?.value?.split(",")?.length ?? 0) == 1) {
              departmentName = value?.editText;
              SharePreferenceUtil.putString(
                  "sp_check_in_is_very_departmentName" +
                      UserRepository.getInstance().getCompanyId(),
                  value?.editText);
            }
            VgEventBus.global
                .send(ClassAndDepartmentIdsEvent(null, value?.value,null));
          }
        });
      }
    });

    // CheckButtonSelectDepartmentWidget.navigatorPush(context, null);
  }

  initCurrentDate() {
    final DateTime nowDateTime = DateTime.now();
    currentTimeByWeekHours =
        DateTime(nowDateTime.year, nowDateTime.month, nowDateTime.day);
  }

  void _pageListener() {
    final int page = pageController.page.round();
    //需求：每次到未刷脸请求未刷脸列表
    if (_currentPage != page && page == 1) {
      refreshMulitiAllListStreamController
          .add(CheckInStatisticsFilterType.unfinishFace);
    }
    if (_currentPage != page && page == 0) {
      refreshMulitiAllListStreamController
          .add(CheckInStatisticsFilterType.finishFace);
    }
    _currentPage = page;
    if (page == 0) {
      filterValueNotifier.value = CheckInStatisticsFilterType.finishFace;
    } else if (page == 1) {
      filterValueNotifier.value = CheckInStatisticsFilterType.unfinishFace;
    }
  }

  @override
  void dispose() {
    for (StreamSubscription item in _streamSubscriptionList) {
      item?.cancel();
    }
    classEventSubscription.cancel();
    deviceEventSubscription.cancel();
    departmentEventSubscription.cancel();
    facedCountValueNotifier?.dispose();
    unFacedCountValueNotifier?.dispose();
    refreshMulitiAllListStreamController?.close();
    changeFilterTypeStreamController?.close();
    // refreshAllListStreamController?.close();
    pageController?.removeListener(_pageListener);
    pageController?.dispose();
    filterValueNotifier?.dispose();
    infoValueNotifier.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Scaffold(
      backgroundColor: ThemeRepository.getInstance().getCardBgColor_21263C(),
      body: _toMainColumnWidget(),
    );
  }

  Widget _toMainColumnWidget() {
    return Column(
      children: <Widget>[
        ///topbar
        /////日期切换bar
        CheckInStatisticsTopBarWidget(),
        _toNetworkStatusWidget(),
        Expanded(
          child: _toExpandedWidget(),
        )
      ],
    );
  }

  ///弱网显示
  Widget _toNetworkStatusWidget() {
    return FutureBuilder(
        future: (Connectivity().checkConnectivity()),
        builder: (context, snapshot) {
          ConnectivityResult result;
          if (snapshot.connectionState == ConnectionState.done) {
            result = snapshot.data;
          }
          return StreamBuilder(
            stream: Connectivity().onConnectivityChanged,
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.active) {
                result = snapshot.data;
              }
              return FutureBuilder(
                future: checkNetwork(),
                builder: (context, connectState) {
                  return Visibility(
                    visible: (ConnectivityResult.none == result ||
                        !(connectState?.data ?? true)),
                    child: Container(
                      color: Color(0x33F95355),
                      height: 40,
                      child: Row(
                        children: [
                          SizedBox(
                            width: 15,
                          ),
                          Image.asset(
                            "images/icon_tip_red.png",
                            width: 16,
                            height: 16,
                          ),
                          SizedBox(
                            width: 6,
                          ),
                          Text(
                            "当前网络不可用，请检查你的网络",
                            style: TextStyle(
                              fontSize: 13,
                              color: Color(0xFFF95355),
                            ),
                          ),
                          Spacer(),
                          GestureDetector(
                            behavior: HitTestBehavior.translucent,
                            onTap: () {
                              refreshMulitiAllListStreamController?.add(null);
                            },
                            child: Container(
                              width: 50,
                              alignment: Alignment.center,
                              child: Text(
                                "刷新",
                                style: TextStyle(
                                  fontSize: 11,
                                  color: Color(0xFFBFC2CC),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                  );
                },
              );
            },
          );
        });
  }

  /// 请求客户端
  Future<bool> checkNetwork() async {
    final dio = Dio();
    try {
      Response response = await dio.get(
        "http://123.207.32.32:8000/api/v1/recommend",
      );
      if (response.statusCode == HttpStatus.ok) {
        return true;
      } else {
        return false;
      }
    } on SocketException catch (_) {
      return false;
    } catch (exception) {
      return false;
    }
  }

  // Widget _toPlaceHoldetWidget() {
  //   return VgPlaceHolderStatusWidget(
  //     loadingStatus: _isLoading,
  //     errorStatus: _isError,
  //     errorOnClick: () =>
  //         _viewModel.getTopInfoHttp(),
  //     child: _toExpandedWidget(),
  //   );
  // }

  Widget _toExpandedWidget() {
    // checkInStatisticsListDataBean = infoValueNotifier?.value;
    return Column(
      children: <Widget>[
        ///筛选按钮
        CheckInStatisticsFilterWidget(
            checkInStatisticsListDataBean: checkInStatisticsListDataBean),

        /// //tabbar
        // CheckInStatisticsTabBarWidget(),
        ///pageview
        // Expanded(
        //   child: CheckInStatisticsPageViewWidget(),
        // ),
        //todo测试用
        // Expanded(
        //   child: CheckInStatisticsListWidget(
        //     groupItemBean: groupInfoDataBean?.groupInfo?.elementAt(0),
        //   ),
        // ),
        /// 显示已刷脸和未刷脸
        ValueListenableBuilder(
          valueListenable: filterValueNotifier,
          builder: (context, filterType, child) {
            return Row(
              children: <Widget>[
                ValueListenableBuilder(
                  valueListenable: facedCountValueNotifier,
                  builder: (BuildContext context, int count, Widget child) {
                    return _SelectTextWidget(
                      text: "已刷脸${count ?? 0}人",
                      isSelected:
                          filterType == CheckInStatisticsFilterType.finishFace,
                      padding: const EdgeInsets.only(left: 15, right: 11),
                      onTap: () {
                        changeFilterTypeAndNotification(
                            CheckInStatisticsFilterType.finishFace, 0);
                      },
                    );
                  },
                ),
                Visibility(
                  visible:classifyType != CheckInStatisticsClassifyType.Device,
                  child: Container(
                    width: 1,
                    height: 12,
                    color: ThemeRepository.getInstance().getLineColor_3A3F50(),
                  ),
                ),
                Visibility(
                  visible:classifyType != CheckInStatisticsClassifyType.Device,
                  child: ValueListenableBuilder(
                    valueListenable: unFacedCountValueNotifier,
                    builder: (BuildContext context, int count, Widget child) {
                      return _SelectTextWidget(
                        text: "未刷脸${count ?? 0}人",
                        isSelected: filterType ==
                            CheckInStatisticsFilterType.unfinishFace,
                        padding: const EdgeInsets.only(left: 11, right: 15),
                        onTap: () {
                          changeFilterTypeAndNotification(
                              CheckInStatisticsFilterType.unfinishFace, 1);
                        },
                      );
                    },
                  ),
                )
              ],
            );
          },
        ),
        Expanded(
          //已刷脸和未刷脸界面
          child: ValueListenableBuilder(
            valueListenable: sortValueNotifier,
            builder: (BuildContext context, CheckInStatisticsSortType type,
                Widget child) {
              return CheckInStatisticsTwoPageViewWidget();
            },
          ),
        ),

        ///底部按钮
        CheckInStatisticsMoreButtonWidget()
      ],
    );
  }

  ///切换过滤器类型并通知
  void changeFilterTypeAndNotification(
      CheckInStatisticsFilterType filterType, int jumpPage) {
    if (filterType == null) {
      return;
    }
    // filterValueNotifier.value = filterType;
    pageController.animateToPage(jumpPage,
        duration: DEFAULT_ANIM_DURATION, curve: Curves.linear);
    // if (filterType == currentFilterType) {
    //   return null;
    // }
    // currentFilterType = filterType;
    // //todo:各项刷新通知
    // refreshAllListStreamController?.add(null);
    // // changeFilterTypeStreamController?.add(null);
    // setState(() {});
  }

  ///修改当前时间
  void changeCurrentDateTime(int dayValue) {
    if (dayValue == null) {
      return;
    }
    if (dayValue > 0) {
      currentTimeByWeekHours =
          currentTimeByWeekHours.add(Duration(days: dayValue.abs()));
    } else if (dayValue < 0) {
      currentTimeByWeekHours =
          currentTimeByWeekHours.subtract(Duration(days: dayValue.abs()));
    } else {
      return;
    }

    ///注意对标当前日期 否者显示错误
    Future.delayed(Duration(milliseconds: 20), () {
      refreshMulitiAllListStreamController?.add(null);
    });
    setState(() {});
  }

  ///修改分类类型
  void changeClassifyType(CheckInStatisticsClassifyType classifyType) {
    this.classifyType = classifyType;
    SharePreferenceUtil.putString(
        "sp_check_in_statistics_is_very_care" +
            UserRepository.getInstance().getCompanyId(),
        classifyType.toString());
    // SharePreferenceUtil.putBool(SP_CHECK_IN_STATISTICS_IS_CLASS,
    //     classifyType == CheckInStatisticsClassifyType.Class);
    // SharePreferenceUtil.putBool(SP_CHECK_IN_STATISTICS_IS_DEPARTMENT,
    //     classifyType == CheckInStatisticsClassifyType.Department);
    if (classifyType != CheckInStatisticsClassifyType.Department ||
        classifyType != CheckInStatisticsClassifyType.Class) {
      refreshMulitiAllListStreamController?.add(null);
      setState(() {});
    }
  }

  @override
  bool get wantKeepAlive => true;
}

/// 选中文本组件
///
/// @author: zengxiangxi
/// @createTime: 3/25/21 11:33 AM
/// @specialDemand:
class _SelectTextWidget extends StatelessWidget {
  final String text;

  final bool isSelected;

  final EdgeInsetsGeometry padding;

  final VoidCallback onTap;

  const _SelectTextWidget(
      {Key key, this.text, this.isSelected = false, this.padding, this.onTap})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      behavior: HitTestBehavior.translucent,
      onTap: onTap,
      child: Container(
        height: 35,
        padding: padding,
        child: Center(
          child: Text(
            text ?? "",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color: isSelected
                  ? ThemeRepository.getInstance().getPrimaryColor_1890FF()
                  : Color(0xFF5E687C),
              fontSize: 12,
            ),
          ),
        ),
      ),
    );
  }
}

class ClassAndDepartmentIdsEvent {
  final String classIds;
  final String departmentIds;
  final String hsns;
  ClassAndDepartmentIdsEvent(this.classIds, this.departmentIds, this.hsns);
}
